import 'dart:math';
import 'dart:developer' as developer;

import 'package:flutter/material.dart';
import 'package:get/get.dart';
// 移除 pull_to_refresh_flutter3 导入，改用 AppBar 按钮刷新
// 移除视频相关导入
import 'package:playtruly/common/models/index.dart';
import 'package:playtruly/common/services/http.dart';
import 'package:playtruly/common/api/index.dart';
import 'package:playtruly/common/api/activity_api.dart';
import 'package:playtruly/common/services/amap_location_service.dart'; // 🗺️ 启用高德地图定位服务
import 'package:playtruly/common/services/permission_service.dart';
import 'package:playtruly/common/services/user_service.dart'; // 🔑 用户服务
import 'package:playtruly/common/utils/toast_util.dart';
import 'package:playtruly/common/services/notification_manager.dart'; // 🔥 导入通知管理器

import 'state.dart';

class HomeController extends GetxController {
  final state = HomeState();
  final HttpService httpService = Get.find<HttpService>();

  // 轮播图数据
  final banners = <String>[].obs;

  // 活动列表数据
  final activities = <ActivityModel>[].obs;

  // 点赞数据
  final likes = <String, bool>{}.obs;

  // 真实数据相关属性
  final nearbyShops = <Shop>[].obs;           // 附近商店列表
  final nearbyComments = <HomeComment>[].obs; // 附近评论列表
  final nearbyActivities = <ActivityData>[].obs; // 附近活动列表（新增）
  final categories = <String>[].obs;          // 分类列表
  final isLoadingNearby = false.obs;          // 加载附近数据状态
  
  // 当前用户信息（从UserService动态获取）
  final RxInt currentUserId = 0.obs;          // 当前用户ID

  // 位置信息
  final locationInfo = "黄岛区井冈山地铁站附近".obs;
  final isDefaultLocation = false.obs;        // 是否为默认位置（用于UI显示）
  
  // 当前用户位置（用于距离计算）- 初始化为烟台莱山区
  final currentUserLatitude = 37.463822.obs;  // 当前用户纬度
  final currentUserLongitude = 121.447935.obs; // 当前用户经度

  // 滚动控制器
  ScrollController? scrollController;
  
  // 下拉刷新相关状态
  final isPullingDown = false.obs;           // 是否正在下拉
  final pullDownOffset = 0.0.obs;           // 下拉偏移量
  final canTriggerRefresh = false.obs;      // 是否可以触发刷新
  final currentPageIndex = 0.obs;           // 当前页面索引
  
  // 下拉刷新配置
  static const double pullThreshold = 80.0;  // 触发刷新的阈值
  static const double maxPullDistance = 120.0; // 最大下拉距离

  // 分类按钮的顶部位置
  final categoryButtonsTop = 0.0.obs;

  // 定位服务依赖（启用高德定位）
  late AmapLocationService _amapLocationService; // 🗺️ 高德地图定位服务
  late PermissionService _permissionService;
  late UserService _userService; // 🔑 用户服务
  
  // 定位状态
  final isLocationLoading = false.obs;

  // 🔥 消息通知小黄点状态管理
  final hasUnreadMessage = false.obs;  // 是否有未读消息

  // 分类按钮的初始位置和吸附位置
  double initialButtonsTop = 0.0;
  double stickyButtonsTop = 0.0;

  // 随机数生成器
  final Random _random = Random();
  
  /// 计算两点间距离（单位：公里）
  /// 使用 Haversine 公式计算地球表面两点间的距离
  double calculateDistance(double lat1, double lon1, double lat2, double lon2) {
    const double earthRadius = 6371; // 地球半径（千米）
    
    final double dLat = _toRadians(lat2 - lat1);
    final double dLon = _toRadians(lon2 - lon1);
    
    final double a = sin(dLat / 2) * sin(dLat / 2) +
        cos(_toRadians(lat1)) * cos(_toRadians(lat2)) *
        sin(dLon / 2) * sin(dLon / 2);
    final double c = 2 * asin(sqrt(a));
    
    return earthRadius * c;
  }
  
  /// 将角度转换为弧度
  double _toRadians(double degree) {
    return degree * pi / 180;
  }

  // 移除视频播放器相关属性，改用静态背景标志
  final useStaticBackground = true.obs;
  
  // 交界线距离顶部的位置
  final borderPositionFromTop = 0.0.obs;

  //瀑布流数据
  final waterfallData = <Map<String, dynamic>>[].obs;

  // 更新位置信息
  void updateLocationInfo(String newLocation, {bool isDefault = false}) {
    locationInfo.value = newLocation;
    isDefaultLocation.value = isDefault;  // 🎯 设置是否为默认位置
    update();
  }

  // 从地图页面更新位置信息
  void updateLocationFromMap(Map<String, dynamic> locationData) {
    try {
      developer.log('🗺️ =============== 接收地图页面位置数据 ===============', name: 'Home');
      
      final address = locationData['address'] as String?;
      final latitude = locationData['latitude'] as double?;
      final longitude = locationData['longitude'] as double?;
      
      if (address != null && latitude != null && longitude != null) {
        // 更新位置信息
        locationInfo.value = address;
        isDefaultLocation.value = false;  // 🎯 用户手动选择的位置，非默认位置
        
        // 更新坐标
        currentUserLatitude.value = latitude;
        currentUserLongitude.value = longitude;
        
        developer.log('✅ 位置信息更新成功:', name: 'Home');
        developer.log('   地址: $address', name: 'Home');
        developer.log('   坐标: $latitude, $longitude', name: 'Home');
        
        // 🎯 重新计算所有项目的距离
        _recalculateAllDistances();
        
        // 🔄 可选：重新加载附近数据（基于新位置）
        // 注释掉避免频繁请求API，只重新计算距离即可
        // _loadNearbyData();
        
        // 显示成功提示
        ToastUtil.success("位置更新 - 已更新到: $address");
        
        // 触发界面更新
        update();
      } else {
        developer.log('❌ 地图返回的位置数据格式不正确', name: 'Home');
      }
      
    } catch (e) {
      developer.log('💥 处理地图位置数据异常: $e', name: 'Home');
    } finally {
      developer.log('🏁 =============== 地图位置数据处理结束 ===============', name: 'Home');
    }
  }

  // 自动检查位置权限并定位（首页启动时调用）
  Future<void> _autoLocationCheck() async {
    try {
      developer.log('🏠 =============== 首页自动定位检查 ===============', name: 'Home');
      developer.log('🔍 开始检查定位服务和权限状态...', name: 'Home');
      
      // 🔍 检查服务依赖是否正确初始化
      developer.log('🔧 定位服务检查: _amapLocationService = $_amapLocationService', name: 'Home');
      developer.log('🔧 权限服务检查: _permissionService = $_permissionService', name: 'Home');
      
      // 检查权限状态
      final hasPermission = _permissionService.isLocationPermissionGranted;
      developer.log('📋 当前权限状态: $hasPermission', name: 'Home');
      
      if (hasPermission) {
        developer.log('✅ 位置权限已授权，开始自动定位', name: 'Home');
        await _performAutoLocation();
      } else {
        developer.log('⚠️ 位置权限未授权，静默请求权限', name: 'Home');
        
        // 静默请求权限（不显示多余的提示）
        final isGranted = await _permissionService.requestLocationPermission();
        developer.log('📋 权限请求结果: $isGranted', name: 'Home');
        
        if (isGranted) {
          developer.log('✅ 权限请求成功，开始自动定位', name: 'Home');
          await _performAutoLocation();
        } else {
          developer.log('❌ 权限请求失败，使用默认位置', name: 'Home');
          _setDefaultLocationInfo();
        }
      }
      
    } catch (e) {
      developer.log('💥 首页自动定位检查异常: $e', name: 'Home');
      developer.log('💥 异常堆栈: ${StackTrace.current}', name: 'Home');
      _setDefaultLocationInfo();
    } finally {
      developer.log('🏁 =============== 首页自动定位检查结束 ===============', name: 'Home');
    }
  }

  // 🗺️ 执行自动定位（学习MyApplication2的实现）
  Future<void> _performAutoLocation() async {
    try {
      isLocationLoading.value = true;
      locationInfo.value = "正在定位中...";
      
      developer.log('🎯 =============== 首页高德定位开始 ===============', name: 'Home');
      developer.log('🔍 准备调用高德定位服务...', name: 'Home');
      developer.log('🔧 高德定位服务状态: ${_amapLocationService.isLocationStarted.value}', name: 'Home');
      developer.log('⚙️ 定位配置: 单次定位, 超时8秒', name: 'Home');
      
      // 🗺️ 策略1: 优先使用高德定位（学习MyApplication2的实现）
      developer.log('🚀 开始调用 _amapLocationService.startLocation...', name: 'Home');
      final amapLocation = await _amapLocationService.startLocation(
        isOnceLocation: true,
        timeout: const Duration(seconds: 8), // 增加超时时间
      );
      developer.log('📬 高德定位服务返回结果: $amapLocation', name: 'Home');
      
      if (amapLocation != null) {
        developer.log('🔍 定位结果详细分析:', name: 'Home');
        developer.log('  ✅ success: ${amapLocation.success}', name: 'Home');
        developer.log('  📍 latitude: ${amapLocation.latitude}', name: 'Home');
        developer.log('  📍 longitude: ${amapLocation.longitude}', name: 'Home');
        developer.log('  🎯 accuracy: ${amapLocation.accuracy}', name: 'Home');
        developer.log('  📍 address: ${amapLocation.address}', name: 'Home');
        developer.log('  ❌ errorCode: ${amapLocation.errorCode}', name: 'Home');
        developer.log('  ❌ errorMessage: ${amapLocation.errorMessage}', name: 'Home');
        
        final isValid = _amapLocationService.isLocationValid(amapLocation);
        developer.log('🔍 位置有效性检查: $isValid', name: 'Home');
      }
      
      if (amapLocation != null && amapLocation.success && _amapLocationService.isLocationValid(amapLocation)) {
        // 🎉 高德定位成功
        final address = _amapLocationService.formatAddress(amapLocation.address);
        final accuracy = _amapLocationService.getAccuracyDescription(amapLocation.accuracy);
        
        // 更新位置信息
        locationInfo.value = address;
        isDefaultLocation.value = false;  // 🎯 标记为真实定位位置
        
        // 更新坐标（用于距离计算）
        currentUserLatitude.value = amapLocation.latitude!;
        currentUserLongitude.value = amapLocation.longitude!;
        
        developer.log('🎉 首页高德定位成功!', name: 'Home');
        developer.log('📍 坐标: ${amapLocation.latitude}, ${amapLocation.longitude}', name: 'Home');
        developer.log('📍 地址: $address', name: 'Home');
        developer.log('🎯 精度: $accuracy', name: 'Home');
        developer.log('🏙️ 城市: ${amapLocation.province} ${amapLocation.city} ${amapLocation.district}', name: 'Home');
        
        // 🎯 重新计算所有项目的距离
        _recalculateAllDistances();
        
        // 🎉 显示定位成功提示（简化为日志）
        developer.log('🎉 定位成功提示: 已获取到您的当前位置: $address', name: 'Home');
        
        return;
      } else {
        // 高德定位失败，使用默认位置
        developer.log('❌ 首页高德定位失败', name: 'Home');
        if (amapLocation != null) {
          developer.log('❌ 定位错误: ${amapLocation.errorMessage} (${amapLocation.errorCode})', name: 'Home');
        } else {
          developer.log('❌ 定位结果为 null', name: 'Home');
        }
      }
      
      // 降级到默认位置
      developer.log('⚠️ 首页定位降级到默认位置', name: 'Home');
      _setDefaultLocationInfo();
      
    } catch (e) {
      developer.log('💥 首页定位异常: $e', name: 'Home');
      developer.log('💥 异常类型: ${e.runtimeType}', name: 'Home');
      developer.log('💥 异常堆栈: ${StackTrace.current}', name: 'Home');
      _setDefaultLocationInfo();
    } finally {
      isLocationLoading.value = false;
      developer.log('🏁 =============== 首页高德定位结束 ===============', name: 'Home');
    }
  }

  // 设置默认位置信息
  void _setDefaultLocationInfo() {
    locationInfo.value = "山东省烟台市莱山区";
    isDefaultLocation.value = true;  // 🎯 标记为默认位置
    currentUserLatitude.value = 37.463822;
    currentUserLongitude.value = 121.447935;
    developer.log('🏠 使用默认位置: ${locationInfo.value}', name: 'Home');
    
    // 🎯 重新计算所有项目的距离
    _recalculateAllDistances();
  }
  
  // 更新交界线位置
  void updateBorderPosition(double position) {
    if (position.isFinite && !position.isNaN) {
      borderPositionFromTop.value = position;
    }
  }

  @override
  void onInit() {
    super.onInit();
    
    developer.log('🏠 =============== HomeController 初始化开始 ===============', name: 'Home');
    
    // 初始化服务依赖（启用高德定位）
    try {
      developer.log('🔧 开始初始化服务依赖...', name: 'Home');
      _amapLocationService = Get.find<AmapLocationService>(); // 🗺️ 高德地图定位服务
      developer.log('✅ AmapLocationService 获取成功', name: 'Home');
      
      _permissionService = Get.find<PermissionService>();
      developer.log('✅ PermissionService 获取成功', name: 'Home');
      
      // 🔑 初始化用户服务，获取真实的当前用户ID
      _userService = Get.find<UserService>();
      developer.log('✅ UserService 获取成功', name: 'Home');
      
      // 🎯 从UserService获取真实的当前用户ID
      if (_userService.isLoggedIn && _userService.currentUser != null) {
        currentUserId.value = _userService.currentUser!.userid;
        developer.log('✅ 从UserService获取用户ID: ${currentUserId.value} (${_userService.currentUser!.username})', name: 'Home');
      } else {
        developer.log('⚠️ 用户未登录，使用默认用户ID: 0', name: 'Home');
        currentUserId.value = 0; // 未登录时使用0作为默认值
      }
    } catch (e) {
      developer.log('💥 服务依赖初始化失败: $e', name: 'Home');
      // 🔄 兜底：如果UserService获取失败，尝试直接使用UserService.to
      try {
        final userService = UserService.to;
        if (userService.isLoggedIn && userService.currentUser != null) {
          currentUserId.value = userService.currentUser!.userid;
          developer.log('✅ 兜底方案获取用户ID: ${currentUserId.value}', name: 'Home');
        } else {
          currentUserId.value = 0;
          developer.log('⚠️ 兜底方案：用户未登录，使用默认ID: 0', name: 'Home');
        }
      } catch (fallbackError) {
        developer.log('💥 兜底方案也失败: $fallbackError', name: 'Home');
        currentUserId.value = 0; // 最终兜底
      }
    }
    
    state.isLoading = true.obs;
    state.articles = <Map<String, dynamic>>[].obs;
    state.isLoadingArticles = false.obs;
    state.currentPage = 1.obs;
    state.totalPages = 1.obs;
    state.hasMoreArticles = true.obs;

    // 初始化滚动控制器
    scrollController = ScrollController();
    scrollController!.addListener(_scrollListener);

    // 🔄 监听用户登录状态变化
    _setupUserListener();
    
    // 加载初始数据
    loadInitialData();
    // 初始化瀑布流数据
    initWaterfallData();
    _initData();
    
    // 🔥 注册通知回调到NotificationManager（延迟注册，确保NotificationManager已初始化）
    Future.delayed(const Duration(milliseconds: 100), () {
      try {
        final notificationManager = NotificationManager.to;
        notificationManager.registerNotificationCallback((hasNotification) {
          hasUnreadMessage.value = hasNotification;
          developer.log('🔔 Home收到NotificationManager通知更新: $hasNotification', name: 'Home');
        });
        developer.log('✅ Home已注册通知回调', name: 'Home');
      } catch (e) {
        developer.log('💥 Home注册通知回调失败: $e', name: 'Home');
        developer.log('🔄 降级方案：保持原有通知功能', name: 'Home');
        // 降级方案：如果NotificationManager不可用，保持原有功能
      }
    });
    
    // 🎯 自动检查位置权限并定位
    developer.log('🎯 准备调用 _autoLocationCheck...', name: 'Home');
    _autoLocationCheck();
    
    // 延迟初始化界面，等待界面加载完成
    WidgetsBinding.instance.addPostFrameCallback((_) {
      // 移除视频初始化
      
      final screenHeight = Get.height;
      initialButtonsTop = screenHeight * 0.6 - 28; // 调整为新的顶部区域高度
      stickyButtonsTop = kToolbarHeight + MediaQuery.of(Get.context!).padding.top; // 吸附位置
      categoryButtonsTop.value = initialButtonsTop;
      
      // 生成随机分布的用户气泡
      generateRandomUserBubbles();
      
      developer.log('🏠 =============== HomeController 初始化完成 ===============', name: 'Home');
    });
  }

  /// 🔄 设置用户状态监听器
  void _setupUserListener() {
    try {
      // 🔄 定期检查用户状态变化（使用公开的getter）
      ever(currentUserId, (int userId) {
        developer.log('🔄 currentUserId变化: $userId', name: 'Home');
      });
      
      // 🔄 启动一个简单的检查器，定期同步用户ID
      Future.doWhile(() async {
        await Future.delayed(const Duration(seconds: 5)); // 每5秒检查一次
        
        final userService = UserService.to;
        int expectedUserId = 0;
        
        if (userService.isLoggedIn && userService.currentUser != null) {
          expectedUserId = userService.currentUser!.userid;
        }
        
        if (currentUserId.value != expectedUserId) {
          currentUserId.value = expectedUserId;
          developer.log('🔄 同步用户ID: $expectedUserId', name: 'Home');
          
          // 🔄 用户状态变化后，重新加载数据以显示正确的"我的活动"状态
          _convertActivitiesToWaterfall();
        }
        
        return true; // 继续循环
      });
      
      developer.log('✅ 用户状态监听器设置成功', name: 'Home');
    } catch (e) {
      developer.log('💥 用户状态监听器设置失败: $e', name: 'Home');
    }
  }

  // 生成随机分布的用户气泡
  void generateRandomUserBubbles() {
    // 保存原始用户数据
    final originalUsers = List<Map<String, dynamic>>.from(state.userBubbles);
    
    // 清空现有数据
    state.userBubbles.clear();
    
    // 圆形分布的参数
    const double minRadius = 40.0; // 最小半径
    const double maxRadius = 120.0; // 最大半径
    
    // 屏幕宽度
    final screenWidth = Get.width;
    
    // 已分配的位置列表，用于避免重叠
    final List<Rect> allocatedAreas = [];
    
    // 为每个用户生成新的随机位置
    for (final user in originalUsers) {
      // 尝试找到一个不重叠的位置
      bool positionFound = false;
      Map<String, dynamic> newUser = Map<String, dynamic>.from(user);
      
      int attempts = 0;
      while (!positionFound && attempts < 20) {
        attempts++;
        
        // 生成随机角度和半径
        final angle = _random.nextDouble() * 2 * 3.14159; // 随机角度（0-2π）
        final radius = minRadius + _random.nextDouble() * (maxRadius - minRadius);
        
        // 计算新的偏移量
        final offsetX = radius * cos(angle);
        final offsetY = radius * sin(angle);
        
        // 计算头像大小（假设为40x40）
        const avatarSize = 40.0;
        
        // 检查是否与已分配区域重叠
        final newRect = Rect.fromLTWH(
          (screenWidth / 2) + offsetX - avatarSize / 2,
          150 + offsetY - avatarSize / 2, // 中心点Y坐标设为150
          avatarSize,
          avatarSize,
        );
        
        bool overlaps = false;
        for (final rect in allocatedAreas) {
          if (rect.overlaps(newRect)) {
            overlaps = true;
            break;
          }
        }
        
        if (!overlaps) {
          positionFound = true;
          allocatedAreas.add(newRect);
          
          newUser['offsetX'] = offsetX;
          newUser['offsetY'] = offsetY;
        }
      }
      
      // 如果尝试多次后仍未找到合适位置，使用原始位置
      if (!positionFound) {
        debugPrint('无法为用户 ${user['name']} 找到不重叠的位置，使用原始位置');
      }
      
      state.userBubbles.add(newUser);
    }
  }

  // 设置滚动控制器
  void setScrollController(ScrollController controller) {
    scrollController = controller;
  }

  // 更新滚动位置，控制分类按钮的动画效果
  void updateScrollPosition(double scrollPosition) {
    // 防止NaN和无穷大值
    if (scrollPosition.isNaN || scrollPosition.isInfinite) {
      return;
    }

    // 当滚动超过一定距离时，将分类按钮吸附到顶部
    if (scrollPosition > 150) { // 增加阈值以适应更大的顶部区域
      if (categoryButtonsTop.value != stickyButtonsTop) {
        categoryButtonsTop.value = stickyButtonsTop;
      }
    } else {
      // 根据滚动位置计算分类按钮的位置，并防止计算出NaN值
      final newPosition = max(stickyButtonsTop, initialButtonsTop - (scrollPosition * 0.5).clamp(0.0, initialButtonsTop - stickyButtonsTop));
      if (!newPosition.isNaN && !newPosition.isInfinite) {
        categoryButtonsTop.value = newPosition;
      }
    }
  }

  // 添加点评评论
  void addReviewComment(String reviewId, String comment) {
    if (comment.isEmpty) return;

    // 查找对应的点评
    final reviewIndex = state.nearbyReviews.indexWhere((review) => review['id'] == reviewId);
    if (reviewIndex == -1) return;

    // 创建新评论
    final newComment = {
      'id': DateTime.now().millisecondsSinceEpoch.toString(),
      'userId': 'current_user',
      'username': '我',
      'avatar': '',
      'content': comment,
      'createdAt': DateTime.now().toIso8601String(),
    };

    // 添加评论到对应点评
    final review = Map<String, dynamic>.from(state.nearbyReviews[reviewIndex]);
    final comments = List<Map<String, dynamic>>.from(review['comments'] ?? []);
    comments.insert(0, newComment);
    review['comments'] = comments;
    review['commentCount'] = comments.length;

    // 更新点评数据
    state.nearbyReviews[reviewIndex] = review;

    ToastUtil.success('评论已发送');
  }

  // 获取点评评论列表
  List<Map<String, dynamic>> getReviewComments(String reviewId) {
    final review = state.nearbyReviews.firstWhereOrNull((review) => review['id'] == reviewId);
    return List<Map<String, dynamic>>.from(review?['comments'] ?? []);
  }

  // 移除所有视频播放器相关方法
  // _initVideoPlayer, _tryPlayLocalVideo, _tryPlayNetworkVideo, _tryPlayBackupVideo, _useFallbackBackground


  // 初始化数据
  void _initData() {
    _loadBannersFromApi(); // 从API加载轮播图
    _loadActivities();
    _loadNearbyData(); // 加载附近数据
  }

  // 加载附近商家和评论数据（现在也加载活动数据）
  Future<void> _loadNearbyData() async {
    try {
      isLoadingNearby.value = true;
      
      print('🔄 =============== 开始首页API调试（使用活动接口）===============');
      
      // 🎯 使用当前用户的真实位置坐标
      final double latitude = currentUserLatitude.value;
      final double longitude = currentUserLongitude.value;
      
      developer.log('🌍 使用坐标加载附近数据: $latitude, $longitude', name: 'Home');
      
      // 🎯 首先加载活动数据（与activity_tab.dart相同）
      try {
        print('🚀 加载活动数据...');
        final activityResponse = await ActivityApi.getNearbyActivities(
          latitude: latitude,
          longitude: longitude,
          radius: 50.0,
          limit: 20,
          page: 1,
        );
        
        if (activityResponse.isSuccess) {
          nearbyActivities.assignAll(activityResponse.data);
          print('✅ 活动数据加载成功: ${nearbyActivities.length}个活动');
          
          // 将活动数据转换为瀑布流格式
          _convertActivitiesToWaterfall();
        } else {
          print('❌ 活动数据加载失败: ${activityResponse.message}');
          nearbyActivities.clear();
        }
      } catch (e) {
        print('💥 活动数据加载异常: $e');
        nearbyActivities.clear();
      }
      
      // 🏪 然后加载商店和评论数据（保留原有功能）
      try {
        print('🚀 加载商店和评论数据...');
        final response = await HomeApi.getNearbyShopsAndComments(
          latitude: latitude,
          longitude: longitude,
          shopLimit: 10,
          page: 1,
          userId: currentUserId.value,
          category: ["餐饮", "娱乐", "购物"],
        );
        
        if (response.isSuccess) {
          // 使用新的数据结构（匹配安卓版）
          nearbyShops.assignAll(response.dataShop);
          
          // 如果有单个评论，添加到列表中
          if (response.dataComment != null) {
            nearbyComments.assignAll([response.dataComment!]);
          } else {
            nearbyComments.clear();
          }
          
          print('✅ 商店和评论数据加载成功: ${nearbyShops.length}个商店, ${nearbyComments.length}条评论');
        } else {
          print('❌ 商店和评论数据加载失败: ${response.message ?? '未知错误'}');
          nearbyShops.clear();
          nearbyComments.clear();
        }
      } catch (e) {
        print('💥 商店和评论数据加载异常: $e');
        nearbyShops.clear();
        nearbyComments.clear();
      }
      
      // 使用默认分类
      categories.assignAll(['餐饮', '娱乐', '购物', '酒店', '其他']);
      
      // 📊 总结加载结果
      final totalItems = nearbyActivities.length + nearbyShops.length + nearbyComments.length;
      print('📊 首页数据加载完成: ${nearbyActivities.length}个活动, ${nearbyShops.length}个商店, ${nearbyComments.length}条评论, 总计${totalItems}项');
      
      // 🎯 如果活动数据为空，添加少量基础数据保证用户体验
      if (nearbyActivities.isEmpty) {
        print('⚠️ API活动数据为空，添加基础展示数据');
        _addBasicWaterfallData();
      }
      
    } catch (e) {
      print('💥 首页数据加载异常: $e');
      // 异常时使用模拟数据
      _loadMockNearbyData();
    } finally {
      isLoadingNearby.value = false;
      print('🏁 =============== 首页API调试结束 ===============');
    }
  }

  // 加载模拟附近数据（作为备用）
  void _loadMockNearbyData() {

    
    // 模拟商店数据
    final mockShops = [
      Shop(
        shopId: 1,
        shopName: "海上鲜美食城",
        shopAddress: "烟台市芝罘区海港路88号",
        shopPhone: "0535-6688888",
        businessHours: "09:00-22:00",
        rating: 4.5,
        distance: 0.5,
        category: "餐饮",
        description: "烟台最新鲜的海鲜美食",
        tags: ["海鲜", "新鲜", "正宗"],
      ),
      Shop(
        shopId: 2,
        shopName: "蓬莱仙境KTV",
        shopAddress: "烟台市蓬莱区仙境路66号",
        shopPhone: "0535-5577777",
        businessHours: "18:00-02:00",
        rating: 4.3,
        distance: 1.2,
        category: "娱乐",
        description: "高端KTV娱乐场所",
        tags: ["KTV", "娱乐", "高端"],
      ),
      Shop(
        shopId: 3,
        shopName: "烟台苹果专卖店",
        shopAddress: "烟台市莱山区苹果街99号",
        shopPhone: "0535-3366666",
        businessHours: "08:00-20:00",
        rating: 4.7,
        distance: 2.1,
        category: "购物",
        description: "烟台特产苹果专卖",
        tags: ["苹果", "特产", "新鲜"],
      ),
    ];
    
    // 模拟评论数据
    final mockComments = [
      HomeComment(
        commentId: 1,
        commentTitle: "海鲜很新鲜",
        commentContent: "刚从海上鲜美食城吃完，海鲜非常新鲜，价格也很实惠！",
        publisherNickname: "海鲜达人",
        likeCount: 23,
        isLiked: false,
        publisherAvatar: "https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_1.webp",
        publishTime: "2小时前",
        shopId: 1,
        rating: 4.5,
      ),
      HomeComment(
        commentId: 2,
        commentTitle: "KTV设备不错",
        commentContent: "蓬莱仙境KTV的音响设备很棒，包厢也很干净，和朋友玩得很开心！",
        publisherNickname: "唱歌小王子",
        likeCount: 15,
        isLiked: true,
        publisherAvatar: "https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_2.webp",
        publishTime: "1天前",
        shopId: 2,
        rating: 4.3,
      ),
      HomeComment(
        commentId: 3,
        commentTitle: "苹果香甜可口",
        commentContent: "烟台苹果真的很棒，又脆又甜，买了一箱送给家人！",
        publisherNickname: "水果爱好者",
        likeCount: 8,
        isLiked: false,
        publisherAvatar: "https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_3.webp",
        publishTime: "3天前",
        shopId: 3,
        rating: 4.7,
      ),
    ];
    
    // 模拟分类数据
    final mockCategories = ["餐饮", "娱乐", "购物", "酒店", "其他"];
    
    // 更新到响应式变量
    nearbyShops.assignAll(mockShops);
    nearbyComments.assignAll(mockComments);
    categories.assignAll(mockCategories);
    

  }

  // 加载轮播图数据
  void _loadBanners() {
    banners.addAll([
      "https://picsum.photos/id/10/500/300",
      "https://picsum.photos/id/20/500/300",
      "https://picsum.photos/id/30/500/300",
    ]);
  }

  // 加载活动数据
  void _loadActivities() {
    // 这里可以添加从API获取活动数据的逻辑
    // 目前使用state.latestActivities中的模拟数据
  }

  // 点赞或取消点赞
  void toggleLike(String id) {
    if (likes.containsKey(id)) {
      likes[id] = !likes[id]!;
    } else {
      likes[id] = true;
    }
    update();
  }

  // 检查是否已点赞
  bool isLiked(String id) {
    return likes[id] ?? false;
  }

  // 滚动监听器
  void _scrollListener() {
    if (scrollController != null) {
      updateScrollPosition(scrollController!.offset);
    }
  }

  // 加载初始数据
  void loadInitialData() {
    state.isLoading.value = true;
    // 这里可以添加API调用逻辑
    Future.delayed(const Duration(milliseconds: 500), () {
      state.isLoading.value = false;
    });
  }

  // 初始化瀑布流数据（删除测试数据，只使用真实API数据）
  void initWaterfallData() {
    state.isLoadingWaterfall.value = true;
    
    print('🎯 初始化瀑布流数据：只使用真实API数据，不再生成测试数据');
    
    // 💡 现在所有数据都通过 _loadNearbyData() -> _convertActivitiesToWaterfall() 来添加
    // 不再生成任何测试数据，完全依赖API返回的真实活动数据
    
    // 初始化为空状态，等待API数据加载
    state.waterfallItems.clear();
    state.isLoadingWaterfall.value = false;
    
    print('✅ 瀑布流数据初始化完成：等待API数据填充');
  }

  // 评论点赞功能
  Future<void> toggleCommentLike(int commentId) async {
    try {
      // 找到评论
      final commentIndex = nearbyComments.indexWhere((comment) => comment.commentId == commentId);
      if (commentIndex == -1) {
        debugPrint('❌ 找不到评论ID: $commentId');
        return;
      }
      
      final comment = nearbyComments[commentIndex];
      final newIsLiked = !comment.isLiked;
      final newLikeCount = newIsLiked ? comment.likeCount + 1 : comment.likeCount - 1;
      
      // 先更新UI（乐观更新）
      nearbyComments[commentIndex] = comment.copyWithLike(
        isLiked: newIsLiked,
        likeCount: newLikeCount,
      );
      

      
      // 调用API
      final success = await HomeApi.likeComment(
        commentId: commentId,
        userId: currentUserId.value,
        isLike: newIsLiked,
      );
      
      if (!success) {
        // 如果API调用失败，回滚UI更新

        nearbyComments[commentIndex] = comment;
        
        ToastUtil.error('操作失败 - 网络异常，请重试');
      } else {

        ToastUtil.success(newIsLiked ? '点赞成功' : '取消点赞');
      }
      
    } catch (e) {

      // 可以在这里处理异常，比如显示错误提示
    }
  }

  // 商店打卡功能
  Future<void> checkInShop(int shopId) async {
    try {

      
      final result = await HomeApi.checkInShop(
        userId: currentUserId.value,
        shopId: shopId,
        action: 'check_in',
      );
      
      if (result != null && result['status'] == 'success') {

        ToastUtil.success('打卡成功 - 获得积分奖励！');
      } else {

        ToastUtil.error('打卡失败 - 请重试');
      }
      
    } catch (e) {

      ToastUtil.error('打卡失败 - 网络异常，请重试');
    }
  }

  // 添加基础展示数据（当API无数据时使用）
  void _addBasicWaterfallData() {
    try {
      // 只添加少量基础数据，避免主线程阻塞
      final basicItems = <WaterfallItem>[
        WaterfallItem(
          id: 'basic_1',
          type: 'image',
          coverUrl: 'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/art_works/share_154f5afcc73ab7814a745378c6dd2846_edit_391954352758421.png',
          imageUrls: ['https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/art_works/share_154f5afcc73ab7814a745378c6dd2846_edit_391954352758421.png'],
          title: '',
          description: '分享生活中的美好瞬间',
          authorName: '生活达人',
          authorAvatar: 'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_1.webp',
          likeCount: 23,
          commentCount: 5,
          dislikeCount: 1,
          aspectRatio: 0.75,
          gender: '女', // 添加性别信息
        ),
        WaterfallItem(
          id: 'basic_2',
          type: 'image',
          coverUrl: 'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/art_works/share_06409c288f6c65c4f600bddf9283602f_edit_391871265051142.png',
          imageUrls: ['https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/art_works/share_06409c288f6c65c4f600bddf9283602f_edit_391871265051142.png'],
          title: '',
          description: '记录每一个值得纪念的时刻',
          authorName: '摄影师',
          authorAvatar: 'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_2.webp',
          likeCount: 45,
          commentCount: 12,
          dislikeCount: 2,
          aspectRatio: 0.8,
          gender: '男', // 添加性别信息
        ),
        WaterfallItem(
          id: 'basic_3',
          type: 'image',
          coverUrl: 'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/post/11.jpg',
          imageUrls: ['https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/post/11.jpg'],
          title: '',
          description: '用镜头捕捉世界的美',
          authorName: '艺术家',
          authorAvatar: 'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_3.webp',
          likeCount: 67,
          commentCount: 8,
          dislikeCount: 0,
          aspectRatio: 0.9,
          gender: '女', // 添加性别信息
        ),
      ];
      
      // 添加到UI
      state.waterfallItems.addAll(basicItems);
      print('✅ 基础展示数据已添加: ${basicItems.length}项');
      
    } catch (e) {
      print('💥 添加基础数据异常: $e');
    }
  }

  // 将活动数据转换为瀑布流格式并添加到UI（异步优化）
  void _convertActivitiesToWaterfall() {
    // 🚀 使用异步处理，避免阻塞主线程
    Future.microtask(() async {
      try {
        final activityWaterfallItems = <WaterfallItem>[];
        
        // 分批处理活动数据，避免一次处理太多数据
        const batchSize = 5;
        for (int i = 0; i < nearbyActivities.length; i += batchSize) {
          final batch = nearbyActivities.skip(i).take(batchSize);
          
          for (final activity in batch) {
            // 🗺️ 计算距离当前用户位置的真实距离
            double realDistance = 0.0;
            if (activity.latitude != 0.0 && activity.longitude != 0.0) {
              realDistance = calculateDistance(
                currentUserLatitude.value,
                currentUserLongitude.value,
                activity.latitude,
                activity.longitude,
              );
            }
            
            // 🎯 调试性别数据
            developer.log('🔍 活动性别数据调试:', name: 'Home');
            developer.log('   活动ID: ${activity.activityId}', name: 'Home');
            developer.log('   发布者: ${activity.publisherNickname}', name: 'Home');
            developer.log('   原始性别: "${activity.publisherGender}"', name: 'Home');
            developer.log('   性别是否为空: ${activity.publisherGender.isEmpty}', name: 'Home');
            
            // 将ActivityData转换为WaterfallItem格式
            final waterfallItem = WaterfallItem(
              id: 'real_activity_${activity.activityId}',
              type: 'activity', // 标记为活动类型
              coverUrl: activity.activityImages.isNotEmpty 
                  ? activity.activityImages.first 
                  : '', // 使用第一张图片
              imageUrls: activity.activityImages, // 所有活动图片
              title: activity.activityTitle.isEmpty ? '未知活动' : activity.activityTitle,
              description: activity.activityDetails.isEmpty ? '暂无详情' : activity.activityDetails,
              authorName: activity.publisherNickname.isEmpty ? '未知用户' : activity.publisherNickname,
              authorAvatar: activity.publisherAvatar.isEmpty ? '' : activity.publisherAvatar,
              likeCount: 0, // 活动暂无点赞功能
              commentCount: 0,
              dislikeCount: 0,
              aspectRatio: 0.75, // 活动卡片固定比例
              // 额外的活动信息
              location: activity.activityLocation.isEmpty ? null : activity.activityLocation,
              distance: realDistance > 0 ? '距离${realDistance.toStringAsFixed(1)}公里' : '距离未知',
              time: activity.timeAgoDescription,
              activityType: activity.activityType.isNotEmpty ? activity.activityType.join(', ') : null,
              activityTags: activity.activityTags.isNotEmpty ? activity.activityTags.join(', ') : null,
              participants: '${activity.activityCurrentParticipants}/${activity.activityMaxParticipants}人',
              publishTime: activity.activityPublishTime.isEmpty ? null : activity.activityPublishTime,
              status: activity.activityStatus.isNotEmpty ? activity.activityStatus.join(', ') : null,
              // 🔑 添加发布者ID和当前用户ID，用于判断是否为自己的活动
              publisherId: activity.publisherId,
              currentUserId: currentUserId.value,
              // 🎯 添加真实的性别信息
              gender: activity.publisherGender.isNotEmpty ? activity.publisherGender : null,
              // 🔥 添加地理位置和活动限制信息
              latitude: activity.latitude, // 传递活动纬度
              longitude: activity.longitude, // 传递活动经度
              activityRestriction: activity.activityRestriction, // 传递活动性别限制
            );
            
            activityWaterfallItems.add(waterfallItem);
          }
          
          // 分批处理时添加短暂延迟，让主线程有时间处理其他任务
          if (i + batchSize < nearbyActivities.length) {
            await Future.delayed(const Duration(milliseconds: 10));
          }
        }
        
        // 🎯 将活动数据插入到现有瀑布流数据的前面（最新优先显示）
        if (activityWaterfallItems.isNotEmpty) {
          // 创建新的列表，活动数据在前
          final allItems = <WaterfallItem>[];
          allItems.addAll(activityWaterfallItems);
          allItems.addAll(state.waterfallItems);
          
          // 更新UI数据源
          state.waterfallItems.assignAll(allItems);
          print('🎨 活动数据转换完成: ${activityWaterfallItems.length}个活动项目已添加到UI');
          print('📱 当前UI总项目数: ${state.waterfallItems.length}');
        }
        
      } catch (e) {
        print('💥 活动数据转换异常: $e');
      }
    });
  }

  // 刷新附近数据
  Future<void> refreshNearbyData() async {
    print('🔄 刷新首页附近数据');
    await _loadNearbyData();
  }
  
  /// 🔄 手动刷新回调（通过AppBar刷新按钮触发）
  Future<void> onRefresh() async {
    try {
      developer.log('🔄 首页手动刷新开始', name: 'Home');
      
      // 防止重复刷新
      if (isLoadingNearby.value) {
        developer.log('⚠️ 正在刷新中，忽略重复请求', name: 'Home');
        return;
      }
      
      // 重新加载所有数据
      await _loadNearbyData();
      
      // 显示刷新成功提示
      ToastUtil.success('刷新完成 - 已加载最新数据');
      
      developer.log('✅ 首页手动刷新完成', name: 'Home');
    } catch (e) {
      developer.log('❌ 首页手动刷新失败: $e', name: 'Home');
      
      // 显示刷新失败提示
      ToastUtil.error('刷新失败 - 请检查网络连接后重试');
    }
  }
  
  // ===== 下拉刷新手势处理方法 =====
  
  /// 🎯 更新当前页面索引
  void updateCurrentPageIndex(int index) {
    currentPageIndex.value = index;
    developer.log('📱 当前页面索引: $index', name: 'Home');
  }
  
  /// 🎯 开始下拉手势
  void onPullStart() {
    // 只有在第一页且不在加载中时才允许下拉刷新
    if (currentPageIndex.value == 0 && !isLoadingNearby.value) {
      isPullingDown.value = true;
      pullDownOffset.value = 0.0;
      canTriggerRefresh.value = false;
      developer.log('🔄 开始下拉手势', name: 'Home');
    }
  }
  
  /// 🎯 更新下拉偏移
  void onPullUpdate(double offset) {
    if (!isPullingDown.value) return;
    
    // 限制下拉距离，使用阻尼效果
    final dampedOffset = offset * 0.6; // 阻尼系数
    pullDownOffset.value = dampedOffset.clamp(0.0, maxPullDistance);
    
    // 检查是否达到触发阈值
    final wasCanTrigger = canTriggerRefresh.value;
    canTriggerRefresh.value = pullDownOffset.value >= pullThreshold;
    
    // 触发震动反馈（当刚好达到阈值时）
    if (canTriggerRefresh.value && !wasCanTrigger) {
      // 这里可以添加震动反馈
      developer.log('✨ 达到刷新阈值', name: 'Home');
    }
    
    developer.log('📏 下拉偏移: ${pullDownOffset.value.toStringAsFixed(1)}, 可触发: ${canTriggerRefresh.value}', name: 'Home');
  }
  
  /// 🎯 结束下拉手势
  Future<void> onPullEnd() async {
    if (!isPullingDown.value) return;
    
    developer.log('🏁 结束下拉手势, 偏移: ${pullDownOffset.value}, 可触发: ${canTriggerRefresh.value}', name: 'Home');
    
    if (canTriggerRefresh.value) {
      // 触发刷新
      developer.log('🚀 触发下拉刷新', name: 'Home');
      await onRefresh();
    }
    
    // 重置状态
    _resetPullState();
  }
  
  /// 🎯 重置下拉状态
  void _resetPullState() {
    isPullingDown.value = false;
    pullDownOffset.value = 0.0;
    canTriggerRefresh.value = false;
    developer.log('🔄 重置下拉状态', name: 'Home');
  }
  
  // 🎯 重新计算所有项目的距离（当用户位置更新时调用）
  void _recalculateAllDistances() {
    try {
      developer.log('🧮 =============== 重新计算所有项目距离 ===============', name: 'Home');
      developer.log('📍 当前用户位置: ${currentUserLatitude.value}, ${currentUserLongitude.value}', name: 'Home');
      
      // 重新计算瀑布流项目的距离
      for (int i = 0; i < state.waterfallItems.length; i++) {
        final item = state.waterfallItems[i];
        
        // 只有活动类型的项目才有坐标信息需要重新计算距离
        if (item.type == 'activity') {
          // 从活动数据中查找对应的坐标
          final activityIdStr = item.id.replaceFirst('real_activity_', '');
          final activityId = int.tryParse(activityIdStr);
          
          if (activityId != null) {
            final activity = nearbyActivities.firstWhereOrNull(
              (activity) => activity.activityId == activityId
            );
            
            if (activity != null && activity.latitude != 0.0 && activity.longitude != 0.0) {
              // 计算真实距离
              final realDistance = calculateDistance(
                currentUserLatitude.value,
                currentUserLongitude.value,
                activity.latitude,
                activity.longitude,
              );
              
              // 更新距离信息
              final updatedItem = WaterfallItem(
                id: item.id,
                type: item.type,
                coverUrl: item.coverUrl,
                imageUrls: item.imageUrls,
                title: item.title,
                description: item.description,
                authorName: item.authorName,
                authorAvatar: item.authorAvatar,
                likeCount: item.likeCount,
                commentCount: item.commentCount,
                dislikeCount: item.dislikeCount,
                aspectRatio: item.aspectRatio,
                location: item.location,
                distance: realDistance > 0 ? '距离${realDistance.toStringAsFixed(1)}公里' : '距离未知',
                time: item.time,
                activityType: item.activityType,
                activityTags: item.activityTags,
                participants: item.participants,
                publishTime: item.publishTime,
                status: item.status,
                publisherId: item.publisherId,
                currentUserId: item.currentUserId,
                gender: item.gender, // 🎯 保持原有的性别信息
                latitude: activity.latitude, // 重新计算距离后，更新纬度
                longitude: activity.longitude, // 重新计算距离后，更新经度
                activityRestriction: item.activityRestriction, // 保持原有的活动限制信息
              );
              
              state.waterfallItems[i] = updatedItem;
              
              developer.log('📏 更新项目距离: ${item.authorName} - ${realDistance.toStringAsFixed(1)}公里', name: 'Home');
            }
          }
        }
      }
      
      developer.log('✅ 距离计算完成，已更新${state.waterfallItems.length}个项目', name: 'Home');
      developer.log('🏁 =============== 距离计算结束 ===============', name: 'Home');
      
    } catch (e) {
      developer.log('💥 重新计算距离异常: $e', name: 'Home');
    }
  }

  // 更新轮播图数据（从API加载）
  Future<void> _loadBannersFromApi() async {
    try {
      final apiBanners = await HomeApi.getBanners();
      if (apiBanners.isNotEmpty) {
        banners.assignAll(apiBanners);

      } else {
        // 如果API没有数据，使用默认数据
        _loadBanners();
      }
    } catch (e) {

      _loadBanners();
    }
  }

  // 🔥 设置消息通知状态（供外部调用）
  void setMessageNotification(bool hasMessage) {
    hasUnreadMessage.value = hasMessage;
    developer.log('🔔 消息通知状态更新: $hasMessage', name: 'Home');
  }

  // 🔥 清除消息通知状态（点击消息图标时调用）
  void clearMessageNotification() {
    hasUnreadMessage.value = false;
    developer.log('🔔 消息通知状态已清除', name: 'Home');
  }

  // 🔥 获取消息通知状态
  bool get messageNotificationStatus => hasUnreadMessage.value;

  /// 🔥 新增：测试加好友消息通知功能（调试用）
  void testFriendRequestMessageNotification() {
    try {
      developer.log('🧪 =============== 主页测试加好友消息通知 ===============', name: 'Home');
      
      // 测试设置通知
      developer.log('🔔 测试设置加好友消息通知...', name: 'Home');
      setFriendRequestMessageNotification(true);
      
      // 显示设置成功提示
      ToastUtil.success('已设置加好友消息通知 - 请检查主页消息图标的小红点');
      
      // 5秒后自动清除通知（方便测试）
      Future.delayed(const Duration(seconds: 5), () {
        developer.log('🔔 自动清除加好友消息通知...', name: 'Home');
        clearFriendRequestMessageNotification();
        ToastUtil.info('已自动清除加好友消息通知');
      });
      
      developer.log('✅ 主页加好友消息通知测试完成', name: 'Home');
      
    } catch (e) {
      developer.log('💥 主页测试加好友消息通知异常: $e', name: 'Home');
      ToastUtil.error('测试失败: $e');
    }
  }

  // 🔥 设置加好友消息通知状态（使用NotificationManager统一管理）
  void setFriendRequestMessageNotification(bool hasNotification) {
    try {
      // 使用NotificationManager统一管理通知状态
      final notificationManager = NotificationManager.to;
      notificationManager.setFriendRequestNotification(hasNotification);
      
      developer.log('🔔 通过NotificationManager设置加好友消息通知: $hasNotification', name: 'Home');
    } catch (e) {
      developer.log('💥 设置加好友消息通知失败: $e', name: 'Home');
      // 降级到本地设置
      setMessageNotification(hasNotification);
    }
  }

  // 🔥 清除加好友消息通知状态（使用NotificationManager统一管理）
  void clearFriendRequestMessageNotification() {
    try {
      // 使用NotificationManager统一管理通知状态
      final notificationManager = NotificationManager.to;
      notificationManager.clearFriendRequestNotification();
      
      developer.log('🔔 通过NotificationManager清除加好友消息通知', name: 'Home');
    } catch (e) {
      developer.log('💥 清除加好友消息通知失败: $e', name: 'Home');
      // 降级到本地清除
      clearMessageNotification();
    }
  }

  @override
  void onClose() {
    // 🔥 取消注册通知回调
    try {
      final notificationManager = NotificationManager.to;
      notificationManager.unregisterNotificationCallback((hasNotification) {
        hasUnreadMessage.value = hasNotification;
      });
      developer.log('✅ Home已取消注册通知回调', name: 'Home');
    } catch (e) {
      developer.log('💥 Home取消注册通知回调失败: $e', name: 'Home');
    }
    
    // 释放滚动控制器
    scrollController?.dispose();
    
    super.onClose();
  }
} 